"""Tag model - 标签词典表（独立标签体系）."""

from __future__ import annotations

from typing import TYPE_CHECKING

from sqlalchemy import Integer, String, Enum as SQLEnum
from sqlalchemy.orm import Mapped, mapped_column, relationship

from ..db.base_class import Base
from ..models.base import TimestampMixin

if TYPE_CHECKING:
    from ..models.lead_tag import LeadTag


class TagCategory(str):
    """标签分类枚举."""

    FACILITY = "facility"  # 配套设施：近地铁、车位、学区房、商圈、医院
    ENVIRONMENT = "environment"  # 环境要求：安静、采光好、朝向南、高楼层、景观好
    SPECIAL = "special"  # 特殊需求：短租、拎包入住、可注册公司、可改造、押一付一
    CUSTOM = "custom"  # 自定义标签


class TagLevel(int):
    """标签优先级（1-3星）."""

    LEVEL_1 = 1  # ⭐ 低优先级
    LEVEL_2 = 2  # ⭐⭐ 中等优先级
    LEVEL_3 = 3  # ⭐⭐⭐ 高优先级（优先匹配）


class Tag(Base, TimestampMixin):
    """标签词典表 - 全局标签管理.

    特性：
    - 3星优先级系统（1-3级），优先从高级别（3星）标签匹配
    - 分类管理（配套、环境、特殊需求、自定义）
    - 使用统计（usage_count）支持热门标签推荐
    - 关键词匹配（keywords）自动映射同义词
    - 每个Lead最多3-4个标签

    示例：
        Tag(name="近地铁", category="facility", level=3, keywords="地铁,轨道,站点")
        Tag(name="学区房", category="facility", level=3, keywords="学区,学校,教育")
        Tag(name="安静", category="environment", level=2, keywords="安静,清静,不吵")
    """

    __tablename__ = "tags"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)

    # 标签基本信息
    name: Mapped[str] = mapped_column(
        String(50), unique=True, index=True, nullable=False, comment="标签名称（唯一）"
    )

    category: Mapped[str] = mapped_column(
        String(20),
        nullable=False,
        index=True,
        default=TagCategory.CUSTOM,
        comment="标签分类：facility/environment/special/custom",
    )

    level: Mapped[int] = mapped_column(
        Integer,
        nullable=False,
        default=TagLevel.LEVEL_2,
        index=True,
        comment="优先级（1-3星），3星优先匹配",
    )

    # 匹配规则
    keywords: Mapped[str | None] = mapped_column(
        String(200),
        nullable=True,
        comment="关键词（逗号分隔），用于AI/规则引擎匹配：'地铁,轨道,站点'",
    )

    description: Mapped[str | None] = mapped_column(String(200), nullable=True, comment="标签描述")

    # 统计信息
    usage_count: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, index=True, comment="使用次数（热度统计）"
    )

    # 状态
    is_active: Mapped[bool] = mapped_column(
        nullable=False, default=True, index=True, comment="是否启用"
    )

    # Relationships
    lead_tags: Mapped[list[LeadTag]] = relationship(
        "LeadTag", back_populates="tag", cascade="all, delete-orphan"
    )

    def __repr__(self) -> str:
        return f"<Tag(id={self.id}, name='{self.name}', level={self.level}, category='{self.category}')>"
